package com.usermanage.servlet.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class UserFilter
 */
@WebFilter("/*")
public class UserFilter implements Filter {

    /**
     * Default constructor. 
     */
    public UserFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		/*判断用户有无登陆，若无登陆，强转*/
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse resp=(HttpServletResponse) response;
		String url1=req.getRequestURI();
		System.out.println("请求的页面为"+url1);
		
		HttpSession session=req.getSession();
//		if (url1.endsWith("login.jsp")||url1.endsWith("register.jsp")||url1.endsWith("CheckCodeServlet")||url1.endsWith("BookManage/")||url1.endsWith("UserServlet?action=login")||url1.endsWith("UserServlet?action=register")) {
//			chain.doFilter(request, response);
//		}else {
//			String name=(String) session.getAttribute("name");
//			if (name==null) {
//				System.out.println("非法进入");
//				resp.getWriter().write("<script language='javascript' type='text/javascript'>alert('请先登录');window.location.href='login.jsp?backurl='+window.location.href;</script>");
//			}
//		}
		if(url1.endsWith("show.jsp")||url1.endsWith("edit.jsp")||url1.endsWith("add.jsp")){
			String name=(String) session.getAttribute("account");
			if (name==null) {
				System.out.println("非法进入");
				resp.getWriter().write("<script language='javascript' type='text/javascript'>alert('请先登录');window.location.href='login.jsp?backurl='+window.location.href;</script>");
			}else {
				chain.doFilter(request, response);
			}
		}else {
			chain.doFilter(request, response);
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
